//
//  ForumPostDetailViewController.m
//  hospitalVIP
//
//  Created by Xiaoyan on 12-12-17.
//  Copyright (c) 2012年 MEETStudio. All rights reserved.
//

#import "ForumPostDetailViewController.h"
#import "PragnantOrderDetailViewController.h"


static ASIHTTPConnection *postDetail_connect;

@interface ForumPostDetailViewController (){
    
    int pageNo;
}

@end

@implementation ForumPostDetailViewController

@synthesize myArray;
@synthesize myTableView;
- (void)dealloc{
    
    
    if (postDetail_connect != nil) {
        postDetail_connect.connectionDelegate = nil;
        [postDetail_connect release];
        postDetail_connect = nil;
    }
    
    [myArray release];
    [myTableView release];
    [heightArray release];
    [super dealloc];
}



- (id)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil
{
    self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil];
    if (self) {
        // Custom initialization
        self.tabBarItem.image = [UIImage imageNamed:@"icon_message.png"];
        self.tabBarItem.title = @"医嘱";
        self.title = @"医嘱";
    }
    return self;
}
- (id)initwithPostId:(NSString *)_postId{
    
    self = [super init];
    if (self) {
        postId = _postId;
    }
    return self;
}



- (void)viewWillAppear:(BOOL)animated{
    
    pageNo = 1;
    //加载数据
    [self.myTableView setContentOffset:CGPointMake(0,-66)];
    [_refreshHeaderView egoRefreshScrollViewDidEndDragging:self.myTableView];

    
    [super viewWillAppear:NO];
}

- (void)viewDidLoad
{
    [super viewDidLoad];
    
    
    NSString *path = [[NSBundle mainBundle] pathForResource:@"bg_pattern_wood" ofType:@"png"];
    self.view.backgroundColor = [UIColor colorWithPatternImage:[UIImage imageWithContentsOfFile:path]];
    
    if (heightArray == nil) {
        heightArray = [[NSMutableArray alloc]init];
    }
    
    [self.navigationController.navigationBar setTintColor:[UIColor blackColor]];
    
    [self refreshView];
    // Do any additional setup after loading the view from its nib.
}

- (void)loadData{
    
    NSString *UserID = [[NSUserDefaults standardUserDefaults] valueForKey:USER_ID];
    
    NSString *urlString = [NSString stringWithFormat:@"%@/MobileHealth/PregnantOrderDataAction.aspx?UserID=%@&CurrPage=%d&PageSize=%d",BASEURL,UserID,pageNo,10];
	NSURL *url = [NSURL URLWithString:urlString];
    
    
    if (postDetail_connect != nil) {
        postDetail_connect.connectionDelegate = nil;
        [postDetail_connect release];
        postDetail_connect = nil;
    }
    
    postDetail_connect = [[ASIHTTPConnection alloc] initGETWithURL:url resultDict:YES isCache:YES];
    postDetail_connect.connectionDelegate = self;
    
    [postDetail_connect startAsynchronous];
    
    
}


#pragma mark connection delegate
- (void)requestFinished:(ASIHTTPConnection *)connection resultDict:(NSDictionary *)dict URL:(NSURL *)url info:(NSDictionary *)info{
    
    [self  headerRefDone];
    [self bottomRefDone];
    

    
    if (myArray == nil) {
        myArray = [[NSMutableArray alloc]init];
    }
    
    if (pageNo == 1) {
        [myArray removeAllObjects];
    }
    
    
     NSArray *array = [dict objectForKey:@"datalist"];
    
    if (array != nil && array.count > 0) {
        
        if (myArray == nil) {
            myArray = [[NSMutableArray alloc]init];
        }
        
        if (pageNo == 1) {
            [myArray removeAllObjects];
        }
        
        [myArray addObjectsFromArray:array];
        [myTableView reloadData];
        [self refreshView];
    }
        
    
}

- (void)requestFailed:(ASIHTTPConnection *)connection error:(NSError *)error URL:(NSURL *)url info:(NSDictionary *)info{
    
    [self  headerRefDone];
    [self bottomRefDone];
    

}

#pragma mark tableView dataSource
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section{
    
    return myArray.count;
    
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath{
    
    static NSString *MyIdentifier = @"postCell";
    
    // Try to retrieve from the table view a now-unused cell with the given identifier.
    UITableViewCell *cell =(UITableViewCell *) [tableView dequeueReusableCellWithIdentifier:MyIdentifier];
    
    if (cell == nil) {
        cell = [[[UITableViewCell alloc] init] autorelease];
        [cell setSelectionStyle:UITableViewCellSelectionStyleNone];
        
        cell.backgroundColor = [UIColor clearColor];
	    cell.selectionStyle = UITableViewCellSelectionStyleNone;
        
        UIImageView *bgview = [[UIImageView alloc]initWithFrame:CGRectMake(5, 5, 310,160 )];
        bgview.image = [[UIImage imageNamed:@"writ bg_staggerer_iPhone.png"] stretchableImageWithLeftCapWidth:100 topCapHeight:20];
        [cell.contentView addSubview:bgview];
        [bgview release];

        
        UILabel *weightLable = [[UILabel alloc]initWithFrame:CGRectMake(20, 35, 150, 25)];
        weightLable.backgroundColor = [UIColor clearColor];
        weightLable.textColor = [UIColor blackColor];
        weightLable.font = [UIFont systemFontOfSize:14];
        [weightLable setTextAlignment:UITextAlignmentLeft];
        [cell.contentView addSubview:weightLable];
        weightLable.tag = 1;
        [weightLable release];
        
        UILabel *bloodPressureLable = [[UILabel alloc]initWithFrame:CGRectMake(160, 35, 150, 25)];
        bloodPressureLable.backgroundColor = [UIColor clearColor];
        bloodPressureLable.textColor = [UIColor blackColor];
        bloodPressureLable.font = [UIFont systemFontOfSize:14];
        [bloodPressureLable setTextAlignment:UITextAlignmentLeft];
        [cell.contentView addSubview:bloodPressureLable];
        bloodPressureLable.tag = 2;
        [bloodPressureLable release];
        
        UILabel *DiastolicPressureLable = [[UILabel alloc]initWithFrame:CGRectMake(20, 60, 150, 25)];
        DiastolicPressureLable.backgroundColor = [UIColor clearColor];
        DiastolicPressureLable.textColor = [UIColor blackColor];
        DiastolicPressureLable.font = [UIFont systemFontOfSize:14];
        [DiastolicPressureLable setTextAlignment:UITextAlignmentLeft];
        [cell.contentView addSubview:DiastolicPressureLable];
        DiastolicPressureLable.tag = 3;
        [DiastolicPressureLable release];
        
        UILabel *SystolicPressureLable = [[UILabel alloc]initWithFrame:CGRectMake(160, 60, 150, 25)];
        SystolicPressureLable.backgroundColor = [UIColor clearColor];
        SystolicPressureLable.textColor = [UIColor blackColor];
        SystolicPressureLable.font = [UIFont systemFontOfSize:14];
        [SystolicPressureLable setTextAlignment:UITextAlignmentLeft];
        [cell.contentView addSubview:SystolicPressureLable];
        SystolicPressureLable.tag = 4;
        [SystolicPressureLable release];
        
        UILabel *UriProteinLable = [[UILabel alloc]initWithFrame:CGRectMake(20, 85, 150, 25)];
        UriProteinLable.backgroundColor = [UIColor clearColor];
        UriProteinLable.textColor = [UIColor blackColor];
        UriProteinLable.font = [UIFont systemFontOfSize:14];
        [UriProteinLable setTextAlignment:UITextAlignmentLeft];
        [cell.contentView addSubview:UriProteinLable];
        UriProteinLable.tag = 5;
        [UriProteinLable release];
        
        
        UILabel *updateTimeLable = [[UILabel alloc]initWithFrame:CGRectMake(15, 5, 150, 25)];
        updateTimeLable.backgroundColor = [UIColor clearColor];
        updateTimeLable.textColor = [UIColor colorWithRed:106.0/255.0 green:192.0/255.0 blue:129.0/255.0 alpha:1.0];
        updateTimeLable.font = [UIFont boldSystemFontOfSize:18];
        [updateTimeLable setTextAlignment:UITextAlignmentLeft];
        [cell.contentView addSubview:updateTimeLable];
        updateTimeLable.tag = 6;
        [updateTimeLable release];
                 
            UIImageView *signImageView = [[UIImageView alloc]initWithFrame:CGRectMake(260, 8, 50, 25)];
            signImageView.image = [UIImage imageNamed:@"dashijianBG_iphone.png"];
            [cell.contentView addSubview:signImageView];
            [signImageView release];
            
            UILabel *signLable = [[UILabel alloc]initWithFrame:CGRectMake(260, 8,50 , 25)];
            signLable.tag = 7;
            signLable.backgroundColor = [UIColor clearColor];
            
            signLable.textColor = [UIColor blackColor];
            signLable.font = [UIFont boldSystemFontOfSize:15];
            signLable.textAlignment = UITextAlignmentCenter;
            [cell.contentView addSubview:signLable];
            [signLable release];
      
            
            UILabel *nameLable = [[UILabel alloc] initWithFrame:CGRectMake(140, 130, 150, 25)];
            nameLable.tag = 8;
            nameLable.backgroundColor = [UIColor clearColor];
            nameLable.textColor = [UIColor blackColor];
            nameLable.font = [UIFont systemFontOfSize:13];
            nameLable.textAlignment = UITextAlignmentRight;
            [cell.contentView addSubview:nameLable];
            [nameLable release];
        
        
        //order
        
        UILabel *orderLable = [[UILabel alloc]initWithFrame:CGRectMake(20, 110, 300, 25)];
        orderLable.backgroundColor = [UIColor clearColor];
        orderLable.textColor = [UIColor blackColor];
        orderLable.font = [UIFont systemFontOfSize:14];
        [orderLable setTextAlignment:UITextAlignmentLeft];
        [cell.contentView addSubview:orderLable];
        orderLable.tag = 9;
        [orderLable release];

        
    }
    
    
    NSDictionary *dict = [myArray objectAtIndex:indexPath.row];
    
    UILabel *lable = (UILabel *)[cell viewWithTag:1];
    lable.text = [NSString stringWithFormat:@"体重：%@Kg",[dict objectForKey:@"Weight"]];
    
    UILabel *lable2 = (UILabel *)[cell viewWithTag:2];
    lable2.text = [NSString stringWithFormat:@"血糖：%@mmol/L",[dict objectForKey:@"BloodSugar"]];
    
    UILabel *lable3 = (UILabel *)[cell viewWithTag:3];
    lable3.text = [NSString stringWithFormat:@"舒张压：%@mmol/L",[dict objectForKey:@"DiastolicPressure"]];
    
    UILabel *lable4 = (UILabel *)[cell viewWithTag:4];
    lable4.text = [NSString stringWithFormat:@"收缩压：%@mmol/L",[dict objectForKey:@"SystolicPressure"]];
    
    UILabel *lable5 = (UILabel *)[cell viewWithTag:5];
    lable5.text = [NSString stringWithFormat:@"尿蛋白：%@mg/L",[dict objectForKey:@"UriaProtein"]];
    
    UILabel *lable6 = (UILabel *)[cell viewWithTag:6];
    lable6.text = [NSString stringWithFormat:@"%@",[[dict objectForKey:@"DataUploadTime"] substringToIndex:10]];
   
    BOOL DataReadState = [[dict objectForKey:@"DataReadState"] boolValue];
    
    UILabel *lable7 = (UILabel *)[cell viewWithTag:7];
    
    if (DataReadState) {
        lable7.text = @"已读";
    }
    else{
        
        lable7.text = @"未读";
    }


    UILabel *lable8 = (UILabel *)[cell viewWithTag:8];
    lable8.textColor = [UIColor colorWithRed:106.0/255.0 green:192.0/255.0 blue:129.0/255.0 alpha:1.0];
    NSString *userName = [dict objectForKey:@"DoctorName"];
    
    lable8.text = [NSString stringWithFormat:@"来自%@医生",userName];
  

    UILabel *lable9 = (UILabel *)[cell viewWithTag:9];
    NSString *order = [dict objectForKey:@"Orders"];
    if (order.length > 20) {
        order = [order substringToIndex:20];
        order = [NSString stringWithFormat:@"%@......",order];
    }
    lable9.text = [NSString stringWithFormat:@"医嘱：%@",order];

    
    return cell;

}


- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath{
    
//    NSDictionary *dict = [myArray objectAtIndex:indexPath.row];
//    
//    NSString *content = [dict objectForKey:@"body"];
//    
//    content = [[PublicMethodEngine sharedPublicMethodEngine] changeStringFommat:content];
//    
//    
//    UIFont *font = [UIFont systemFontOfSize:14];
//    CGSize size = CGSizeMake(300,2500);
//    CGSize labelsize = [content sizeWithFont:font constrainedToSize:size lineBreakMode:UILineBreakModeCharacterWrap];
//    
//    if (indexPath.row == 0) {
//        return labelsize.height + 80;
//
//    }
//    else{
//        
//         return labelsize.height + 60;
//    }
    
    return 170;
   
}



- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath{
    
    NSDictionary *dict = [myArray objectAtIndex:indexPath.row];
    
    PragnantOrderDetailViewController *con = [[PragnantOrderDetailViewController alloc]initWithOrderDict: dict];
    con.hidesBottomBarWhenPushed = YES;
    [self.navigationController pushViewController:con animated:YES];
    [con release];
    
}

- (void)didReceiveMemoryWarning
{
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}



#pragma mark -
#pragma mark Table 下拉刷新
#pragma mark -
#pragma mark Data Source Loading / Reloading Methods


- (void)refreshView
{
    
    //顶部刷新条
    if ( _refreshHeaderView == nil) {
        
        _refreshHeaderView = [[EGORefreshTableHeaderView alloc] initWithFrame:CGRectMake(0.0f, 0.0f- self.myTableView .bounds.size.height, 320, self.myTableView.bounds.size.height)];
        _refreshHeaderView.delegate = self;
        [self.myTableView addSubview:_refreshHeaderView];
    }
    
    
    //底部刷新条
    if ( _refreshTailView == nil) {
        
        _refreshTailView = [[EGORefreshTableTailView alloc] initWithFrame:CGRectMake(0.0f, self.myTableView.contentSize.height, 320, self.myTableView.frame.size.height)];
        _refreshTailView.delegate = self;
        [self.myTableView addSubview:_refreshTailView];
        
    }
    
    if (_refreshTailView != nil) {
        float height = MAX(self.myTableView.contentSize.height, self.myTableView.frame.size.height);
        [_refreshTailView setFrame:CGRectMake(0.0f, height, 320, self.myTableView.frame.size.height)];
    }
    
    
}



//顶部刷新事件
- (void)headerRefData
{
    _HeaderReloading = YES;
    pageNo = 1;
    [self loadData];
    
}

- (void)headerRefDone
{
    _HeaderReloading = NO;
    [_refreshHeaderView egoRefreshScrollViewDataSourceDidFinishedLoading:self.myTableView];
}

//底部刷新事件
- (void)bottomRefData
{
    
    
    _TailReloading = YES;
    
    pageNo = myArray.count/20 +1;
    
    [self loadData];
    
}

- (void)bottomRefDone
{
    _TailReloading = NO;
    if (_refreshTailView != nil) {
        
        [_refreshTailView egoRefreshScrollViewDataSourceDidFinishedLoading:self.myTableView];
    }
    
}



#pragma mark -
#pragma mark UIScrollViewDelegate Methods

- (void)scrollViewWillBeginDragging:(UIScrollView *)scrollView{
}


- (void)scrollViewDidScroll:(UIScrollView *)scrollView{
    
    
    [_refreshHeaderView egoRefreshScrollViewDidScroll:scrollView];
    
    //上拉
    if (_refreshTailView != nil) {
        
        [_refreshTailView egoRefreshScrollViewDidScroll:scrollView];
    }
    
}

- (void)scrollViewDidEndDragging:(UIScrollView *)scrollView willDecelerate:(BOOL)decelerate{
	
    
    [_refreshHeaderView egoRefreshScrollViewDidEndDragging:scrollView];
    //上拉
    if (_refreshTailView != nil) {
        
        [_refreshTailView egoRefreshScrollViewDidEndDragging:scrollView];
    }
    
    
}

- (void)scrollViewDidEndDecelerating:(UIScrollView *)scrollView{
    
}


#pragma mark -
#pragma mark EGORefreshTableTailDelegate Methods

- (void)egoRefreshTableTailDidTriggerRefresh:(EGORefreshTableTailView*)view{
	
	[self bottomRefData];
    
}

- (BOOL)egoRefreshTableTailDataSourceIsLoading:(EGORefreshTableTailView*)view{
	
    
    return _TailReloading;
	
}

- (NSDate*)egoRefreshTableTailDataSourceLastUpdated:(EGORefreshTableTailView*)view{
	
	return [NSDate date]; // should return date data source was last changed
	
}

#pragma mark -
#pragma mark EGORefreshTableHeaderDelegate Methods

- (void)egoRefreshTableHeaderDidTriggerRefresh:(EGORefreshTableHeaderView *)view{
    
	[self headerRefData];
	
}

- (BOOL)egoRefreshTableHeaderDataSourceIsLoading:(EGORefreshTableHeaderView *)view{
	
	//return _reloading; // should return if data source model is reloading
    return _HeaderReloading;
	
}

- (NSDate*)egoRefreshTableHeaderDataSourceLastUpdated:(EGORefreshTableHeaderView *)view{
	
	return [NSDate date]; // should return date data source was last changed
	
}



@end
